from flask import Flask, Response, send_from_directory, jsonify, render_template_string
from flask_cors import CORS
import cv2, os
from main import set_system_running

def servera():
    app = Flask(__name__)
    CORS(app)

    # ---------------- 视频流 ----------------
    cap = cv2.VideoCapture(0)

    def gen_frames():
        while True:
            success, frame = cap.read()
            if not success:
                continue
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

    @app.route('/video_feed')
    def video_feed():
        return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')

    # ---------------- 录像 ----------------
    REC_DIR = "recordings"
    os.makedirs(REC_DIR, exist_ok=True)

    @app.route('/recordings')
    def recordings():
        files = [f for f in os.listdir(REC_DIR) if os.path.isfile(os.path.join(REC_DIR, f))]
        return jsonify(files)

    @app.route('/recordings/<filename>')
    def download_recording(filename):
        return send_from_directory(REC_DIR, filename, as_attachment=True)

    # ---------------- 控制识别 ----------------
    @app.route('/start_recognition')
    def start_recognition():
        set_system_running(True)
        return jsonify({"status": "started"})

    @app.route('/stop_recognition')
    def stop_recognition():
        set_system_running(False)
        return jsonify({"status": "stopped"})

    # ---------------- 首页网页 ----------------
    INDEX_HTML = """
    <!doctype html>
    <html lang="zh-CN">
    <head>
    <meta charset="utf-8">
    <title>智能门神系统</title>
    <style>
        body { font-family: Arial; margin:0; padding:0; background:#f0f0f0;}
        h1 { text-align:center; color:#2c3e50; padding:20px 0;}
        .container { display:flex; flex-wrap:wrap; justify-content:center; padding:0 20px;}
        .video-box, .recordings-box { background:#fff; padding:15px; margin:10px; border-radius:10px;
                                      box-shadow:0 2px 8px rgba(0,0,0,0.2);}
        .video-box { flex:1 1 600px; max-width:700px;}
        .recordings-box { flex:1 1 300px; max-width:400px;}
        video, img { width:100%; border-radius:10px;}
        .btn { padding:10px 20px; margin:10px 5px; font-size:16px; cursor:pointer;
               border:none; border-radius:5px; color:white;}
        .start { background:#27ae60;}
        .stop { background:#e74c3c;}
        .recording-item { margin-bottom:10px; }
        a { text-decoration:none; color:#3498db;}
    </style>
    </head>
    <body>
    <h1>智能门神系统</h1>
    <div class="container">
        <div class="video-box">
            <h2>实时视频流</h2>
            <img src="/video_feed" id="video_feed">
            <div>
                <button class="btn start" onclick="fetch('/start_recognition')">启动识别</button>
                <button class="btn stop" onclick="fetch('/stop_recognition')">停止识别</button>
            </div>
        </div>
        <div class="recordings-box">
            <h2>录像列表</h2>
            <div id="recordings_list"></div>
        </div>
    </div>

    <script>
    async function loadRecordings() {
        const res = await fetch('/recordings');
        const files = await res.json();
        const list = document.getElementById('recordings_list');
        list.innerHTML = '';
        files.forEach(f => {
            const div = document.createElement('div');
            div.className = 'recording-item';
            div.innerHTML = `
                <video controls src="/recordings/${f}"></video>
                <a href="/recordings/${f}" download>下载</a>
            `;
            list.appendChild(div);
        });
    }

    // 页面加载和每5秒刷新一次录像列表
    loadRecordings();
    setInterval(loadRecordings, 5000);
    </script>
    </body>
    </html>
    """

    @app.route('/')
    def index():
        return render_template_string(INDEX_HTML)

    # 运行服务器
    app.run(host="0.0.0.0", port=5000, threaded=True)

# 如果直接运行该文件，仍可启动服务器
if __name__ == "__main__":
    servera()
